package org.haredot.utils;

import com.github.jarod.qqwry.IPZone;
import com.github.jarod.qqwry.QQWry;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class IpUtils {

    /**
     * 获取 客户端 访问的 ip地址
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request){

        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("X-Real-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }

        if ("0:0:0:0:0:0:0:1".equals(ipAddress)) {
            ipAddress = "127.0.0.1" ;
        }

        return ipAddress;
    }

    /**
     * 获取 IP的真实地址
     * @param ip
     * @return
     */
    public static String getRealAddress(String ip, boolean isDetail) {
        try {
            QQWry qqWry = new QQWry();

            IPZone zone = qqWry.findIP(ip);

            if (isDetail) {
                return zone.getMainInfo() + zone.getSubInfo();
            }
            return zone.getMainInfo() ;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getRealAddress(String ip) {
        return getRealAddress(ip, false);
    }
}
